#pragma once

#include "form/IControlBar.h"
#include "form/IControl.h"
#include "ControlBars.h"

class ControlBars;

template<typename T>
class ControlBar: public T
{
	typedef std::map<uint32,sys::ObjectPtr> ControlDictionary;
	enum {ERROR_ID  = 0U};

public:
	BEGIN_DEFINE_CLASS(CLASSID_NULL)
		DEFINE_INTERFACE_ENTRY(IControlBar)
	END_DEFINE_CLASS()

	ControlBar(){m_controlbars = NULL;}
	virtual ~ControlBar(){}

	virtual uint32 GetControls(ControlList& controls) const
	{
		ControlDictionary::const_iterator itbegin = m_controls.begin();
		ControlDictionary::const_iterator itend = m_controls.end();
		for (; itbegin != itend; ++itbegin)
			controls.push_back(itbegin->second.P());

		return controls.size();
	}
	virtual bool ContainControl(uint32 localid)
	{
		return ( m_controls.find(localid) != m_controls.end() );
	}
	virtual IObject* FindControl(uint32 localid) const
	{
		ControlDictionary::const_iterator itfind = m_controls.find(localid);
		if (itfind != m_controls.end())
			return itfind->second.P();
		return NULL;
	}
	virtual void SetControlbars(IControlBars* controlbars){m_controlbars = controlbars;}
	event_implement(ErrorEventHandler,Error);

protected:
	IObject* AddControl(vclsid clsidcontrol) 
	{
		ASSERT(clsidcontrol != CLASSID_NULL);

		sys::ObjectPtr objControl;
		VRVERIFY(objControl.CreateObject(clsidcontrol));
		if (objControl.IsNotNull())
		{
			if (GetControlBars()->RegisterControl(objControl.P()))
			{
				sys::InterfacePtr<IControl> pIFControl(objControl);
				m_controls.insert(std::make_pair(pIFControl->GetCommandID(),objControl));
				return objControl.P();
			}
		}
		return NULL;
	}
	ControlBars* GetControlBars(){return (ControlBars*)m_controlbars;}

private:
	IControlBars* m_controlbars;
	ControlDictionary m_controls;
};

